package com.uy.cuantoconocesdeuruguay.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.widget.Toast;

import com.uy.cuantoconocesdeuruguay.MainActivity;
import com.uy.cuantoconocesdeuruguay.R;
import com.uy.cuantoconocesdeuruguay.controllers.GoogleAnalyticsTracker;

public class ImagesFetcher {
	private boolean done;
	
	public Drawable fetchImage(final Activity activity, String imageURL, boolean isPicture){
		InputStream is = null;
		done = false;
		while (!done){ 
			try {
				is = (InputStream) new URL(imageURL).getContent();
				Drawable fetchedDrawable = Drawable.createFromStream(is, imageURL);
				done = true;
				return fetchedDrawable;
	        } catch (Exception e) {
				GoogleAnalyticsTracker.trackException(activity, e);
	        	e.printStackTrace();
	        	try {
	        		if (isPicture){
		        		MainActivity.instance.runOnUiThread(new Runnable() {
		        		    public void run() {
		    	        		Toast.makeText(
		    	        			activity, 
		    	        			activity.getString(R.string.image_base_activity_image_fetch_error) ,  
	    	        				Toast.LENGTH_SHORT).show();
		        		    }
		        		});
	        		}else{
	        			done = true;
	        		}
					Thread.sleep(3000);
				} catch (InterruptedException e1) {
//					GoogleAnalyticsTracker.trackException(activity, e1);
					done = true;
					e1.printStackTrace();
				}
	        } finally{
	        	if (is != null){
	        		try {
	        			is.close();
					} catch (IOException e) {
						GoogleAnalyticsTracker.trackException(activity, e);
						e.printStackTrace();
					}
	        	}
	        }
		}
		return null;
	}

	public void onCancel() {
		done = true;
	}	
}